package com.liry.security.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import com.liry.security.config.CacheManager;
import com.liry.security.domain.AuthConstant;
import com.liry.security.service.AuthService;
import java.io.IOException;
import java.util.Base64;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Service;

/**
 * 认证
 *
 * @author ALI
 * @since 2023/6/10
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private MathGenerator mathGenerator;

    @Override
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 45, 4, 4);
        // 自定义验证码内容为四则运算方式
        captcha.setGenerator(mathGenerator);
        // 重新生成code
        captcha.createCode();
        String code = captcha.getCode();
        String id = request.getSession().getId();
        cacheManager.set(AuthConstant.buildCaptchaKey(id), code, 2L, TimeUnit.MINUTES);
        try (ServletOutputStream os = response.getOutputStream()) {
            // 这里通过base64加密再返回给前端，前端就不用处理了
            os.write(Base64.getEncoder().encode(captcha.getImageBytes()));
        } catch (IOException e) {
            throw new RuntimeException("验证码异常！");
        }
    }

    @Override
    public boolean validCaptcha(HttpServletRequest request) {
        String id = request.getSession().getId();
        String key = AuthConstant.buildCaptchaKey(id);
        Object match = cacheManager.get(key);
        if (match == null) {
            throw new RuntimeException("验证码过期！");
        }
        // 注意这里的验证码参数不是从body里获取的
        boolean captcha = mathGenerator.verify(match.toString(), request.getParameter("captcha"));
        if (captcha) {
            // 验证成功删除
            cacheManager.delete(key);
        }
        return captcha;
    }
}
